package red.internal.core.codec;

import io.netty.buffer.ByteBuf;
import red.internal.core.message.CacheMessage;
import red.internal.core.message.Message;

/**
 * @author Jin Zheng
 * @since 2020-07-13
 */
public class CacheMessageCodec extends AbstractMessageCodec
{
	public CacheMessageCodec()
	{
	}

	@Override
	protected void encodeBody(Message message, ByteBuf out)
	{
		super.encodeBody(message, out);
		CacheMessage cacheMessage = (CacheMessage) message;
		out.writeInt(cacheMessage.getState().value());
		out.writeBoolean(cacheMessage.isCompress());
		out.writeInt(cacheMessage.getCommand().value());
		this.writeString(cacheMessage.getKey(), out);
		this.writeBytes(cacheMessage.getValue(), out);
		out.writeLong(cacheMessage.getTtl());
	}

	@Override
	protected void decodeBody(Message message, ByteBuf in)
	{
		super.decodeBody(message, in);
		CacheMessage cacheMessage = (CacheMessage) message;
		cacheMessage.setState(in.readInt());
		cacheMessage.setCompress(in.readBoolean());
		cacheMessage.setCommand(in.readInt());
		cacheMessage.setKey(this.readString(in));
		cacheMessage.setValue(this.readBytes(in));
		cacheMessage.setTtl(in.readLong());
	}

	@Override
	public Message getMessage()
	{
		return new CacheMessage();
	}
}
